# @Project: diablo
# @File: offline_by_oe
# @Time: 2023/10/27 16:48
# @User: Jolly
# @Email: jolly@007vin.com

"""
给库存进行批量下架，根据oe信息
"""

import datetime
import json

# 定价来源：客户提供的excel

import requests
import time
import threading
from queue import Queue

from io import BytesIO
from openpyxl import load_workbook
from pymongo import MongoClient
from pymongo.errors import ConnectionFailure


class BatchStockOffline:

    def __init__(self, merchant_id, file_path):

        self.merchant_id = merchant_id
        self.file_path = f"./{file_path}.xlsx"

        start_time = time.time()

        # 初始化数据库连接
        # 2.0生产库
        self.diablo_conn_2_0 = self.get_mongo_connection("root", "aa123456", "192.168.191.175", "27017")

        # 执行任务
        self.task()

        print("========= 数据插入,共耗时:{}'s =========".format(round(time.time() - start_time, 3)))

    def get_mongo_connection(self, username, password, host, port):
        try:
            # 创建 MongoClient
            client = MongoClient(f"mongodb://{username}:{password}@{host}:{port}",
                                 maxPoolSize=150,
                                 minPoolSize=1,
                                 maxIdleTimeMS=30000,
                                 waitQueueTimeoutMS=2000)

            # 检测连接是否可用，如果连接不可用则抛出异常
            if not client:
                raise ConnectionFailure("从MongoDB连接池中获取连接失败！")

            return client

        except ConnectionFailure as e:
            # 处理连接失败的异常
            print(f"连接MongoDB失败: {e}")
            return None

    # 通过oe号获取库存数据
    def get_stock_by_oe(self, oe, origin_quality):

        stocks_identify = []

        if oe:
            connection = self.diablo_conn_2_0

            try:
                if connection is not None:
                    # 执行数据库操作
                    db = connection["inventory_data"]
                    conn = db["ChangYuan_meta_stocks"]

                    filter_dict = {
                        "opid": oe,
                        "ori_quality": origin_quality,
                        "erp_uid": {"$in": ["T0000002_4TH0WP2OQ_T", "T0000002_4TH0WP2OQ_Z1"]}
                    }
                    docs = conn.find(filter_dict, {'identify': 1})

                    for doc in docs:
                        identify_dict = {'identify': doc.get("identify", "")}

                        stocks_identify.append(identify_dict)

            except Exception as e:
                print("获取用户库存数据identify失败 - mongo：", e)
            finally:
                # 将连接放回连接池
                connection.close()

        return stocks_identify

    # 写入数据
    def update_data(self, *args):

        oe = args[0]
        origin_quality = args[1]

        stocks_identify = []

        # 因为oe可能会被去除0，所以补齐三次，三次都没有则记录
        for i in range(0, 5):

            # 通过oe号和原始品质查找库存记录，可能有多个
            stocks_identify = self.get_stock_by_oe(oe, origin_quality)

            if len(stocks_identify) == 0:

                if i != 4:
                    oe = "0" + oe
                    continue
                else:
                    with open("./not_hit.txt", "a") as file:
                        file.write(oe + "\n")

                    return
            else:
                break

        # 找到对应多条记录后，遍历获取identify，然后写入到agreement_price表中
        for identify in stocks_identify:

            # 更新改库存为下架
            filter_dict = {
                "identify": identify.get("identify")
            }

            update_dict = {
                "status": 0
            }

            # 获取2.0MongoDB连接
            connection = self.diablo_conn_2_0

            try:
                if connection is not None:
                    # 执行数据库操作
                    db = connection["inventory_data"]
                    conn = db["ChangYuan_meta_stocks"]
                    conn.update_one(filter=filter_dict, update={'$set': update_dict})

                # 写入下架缓存表
                identifies = [identify.get("identify")]
                res = self.write_removed(identifies)

                print("写入下架缓存表：", identifies, ", ", identifies[0], ",  ", res)

                if res.get('code') != 1:
                    with open("./not_hit_buff.txt", "a") as file:
                        file.write(identify.get("identify") + "\n")

            except Exception as e:
                print("更新2.0MongoDB数据库库存失败：", e)
            finally:
                # 将连接放回连接池
                connection.close()

    def write_removed(self, identifies: list, action='put_off'):
        """
        写入到下架缓存表
        """
        url = 'http://192.168.191.245:11181/v2/openapi/stocks/part/delete'
        params = {'identifies': identifies, 'action': action, 'erp_type': 'ChangYuan'}
        res = requests.post(url=url, json=params).json()
        return res

    # 获取excel数据，生成器返回
    def get_excel_data(self):

        with open(self.file_path, "rb") as file:
            content = file.read()

        # 将内容转换为BytesIO对象
        bytesIO = BytesIO(content)

        # 加载工作簿
        book = load_workbook(bytesIO, read_only=True)

        # 获取活动工作表
        sheet = book.active

        previous = next(sheet.iter_rows(), None)
        for row in sheet.iter_rows():
            yield previous, False
            previous = row
        yield previous, True

    def get_all_excel_data(self):
        """
        获取全部excel
        """

        with open(self.file_path, "rb") as file:
            content = file.read()

        # 将内容转换为BytesIO对象
        bytesIO = BytesIO(content)

        # 加载工作簿
        book = load_workbook(bytesIO, read_only=True)

        # 获取活动工作表
        sheet = book.active

        return sheet.iter_rows()

    # 任务执行
    def task(self):
        q = Queue(maxsize=100)  # 设定最大队列数和线程数

        count = 1

        all_data = self.get_all_excel_data()

        for row in all_data:
            oe = str(row[0].value)
            origin_quality = str(row[1].value)

            t = threading.Thread(target=self.update_data, args=(oe, origin_quality))
            q.put(t)
            if q.full() == True:
                thread_list = []
                while q.empty() == False:
                    t = q.get()
                    thread_list.append(t)
                    t.start()
                for t in thread_list:
                    t.join()

            print("当前写入数：", count, " oe为：", oe, "原始品质为：", origin_quality)

            count += 1

        # 处理残余队列数据
        thread_list = []
        while q.empty() == False:
            t = q.get()
            thread_list.append(t)
            t.start()
        for t in thread_list:
            t.join()


if __name__ == "__main__":
    file_list = ["xiajia2023102701", "xiajia2023102702", "xiajia2023102703"]
    
    for file_path in file_list:
        print(f"当前刷写的是-------------------{file_path}----------------------------")
        BatchStockOffline(3, file_path)

    # BatchStockOffline(3, "xiajia2023102703")

